package proj.unions.resource;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;

import proj.unions.general.L;
import proj.unions.general.OnMyCallBack;
import proj.unions.general.OnMyClickedListener;
import proj.unions.general.ProperTiesCondefine;
import proj.unions.general.PropertiesData;
import proj.unions.general.SCDialog;
import proj.unions.general.SuperTools;
import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.util.Xml;

public class CheckGameResVersion implements Runnable, RMConstDefine {
	
	private Activity mActivity = null;
	private OnMyCallBack mOnMyCallBack = null;
	
	private static String MD5FileName = null;
	
	public CheckGameResVersion(Activity a, OnMyCallBack l, JSONObject json)
	{
		mActivity = a;
		mOnMyCallBack = l;
		
		MD5FileName = SuperTools.getInstance().getDownloadResPath() + "versions.txt";
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		if (mActivity == null || mOnMyCallBack == null)
		{
			mOnMyCallBack.onReceive("error", 0, null);
			return;
		}

		try {
			try {
				checkAssertLibAndRes();
			} catch (NameNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(!ResManager.isSimpleMode)
			check();
		else
			mOnMyCallBack.onReceive("yes", -1, null);
	}
	
	private void check()
	{
		String address = PropertiesData.getInstance().getString(ProperTiesCondefine.HOST_URL);
		String versionCode = SuperTools.getInstance().getVersionCode();
		String unionId = PropertiesData.getInstance().getString(ProperTiesCondefine.UNION_ID);
		
		String temp_lib = SuperTools.getInstance().readLocalFile(KEY_CLIENT_VERSION_LIB);
		String temp_res = SuperTools.getInstance().readLocalFile(KEY_CLIENT_VERSION_RES);
		if(temp_lib.equals(""))
			temp_lib = "-1";
		if(temp_res.equals(""))
			temp_res = "-1";
		
		String url = PropertiesData.getInstance().getString(ProperTiesCondefine.CHECK_RES_URL, address, temp_lib, temp_res, unionId);
		
		int code = -1;
		try {
			HttpGet getMethod = new HttpGet(url);
			HttpClient httpClient = new DefaultHttpClient();
			HttpResponse response = httpClient.execute(getMethod);
			code = response.getStatusLine().getStatusCode();
			if (code == 200)
			{
				InputStream is = response.getEntity().getContent();
				try {
					parse(is);
					return;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		SuperTools.getInstance().showErrorDialog("网络", "网络连接异常，请联系管理员! Error:" + code);
		L.d("网络连接异常，请联系管理员! Error:" + code);
		mOnMyCallBack.onReceive("yes", -1, null);
	}

	private void parse(InputStream is) throws Exception
	{
		byte[] buffer = new byte[1024];
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		int count = 0;
		while((count=is.read(buffer)) != -1)
		{
			bos.write(buffer, 0, count);
		}
		buffer = bos.toByteArray();
		ByteArrayInputStream bis = new ByteArrayInputStream(buffer);
		
		JSONObject json = new JSONObject();
		
		XmlPullParser parser = Xml.newPullParser();
		parser.setInput(bis,"UTF-8");
		int eventType = parser.getEventType();
		while(eventType != XmlPullParser.END_DOCUMENT)
		{
			switch(eventType)
			{
			case XmlPullParser.START_DOCUMENT:
				break;
			case XmlPullParser.START_TAG:
				String startName = parser.getName();
				
				if(parser.getName().equals("update"))
				{
					int attributeCount = parser.getAttributeCount();
					for(int i = 0; i < attributeCount; ++i)
					{
						String name = parser.getAttributeName(i);
						String value = parser.getAttributeValue(i).trim();
						if(name.equals(KEY_NEWEST_VERSION))
						{
							String data[] = value.split(",");
							json.put(KEY_NEWEST_VERSION_LIB, Integer.valueOf(data[0]));
							json.put(KEY_NEWEST_VERSION_RES, Integer.valueOf(data[1]));
						}
						else if(name.equals(KEY_CLIENT_VERSION))
						{
							String data[] = value.split(",");
//							json.put("clientVersion_lib", Integer.valueOf(data[0]));
//							json.put("clientVersion_res", Integer.valueOf(data[1]));
						}
						else if(name.equals(KEY_NEED_UPDATE))
						{
							json.put(KEY_NEED_UPDATE, Boolean.valueOf(value));
						}

						else if(name.equals("cdn"))
						{
							json.put(KEY_CDN_URL, value);
						}
					}
				}
				else if(parser.getName().equals("file"))
				{
					int attributeCount = parser.getAttributeCount();
					for(int i = 0; i < attributeCount; ++i)
					{
						String name = parser.getAttributeName(i);
						String value = parser.getAttributeValue(i).trim();
						if(name.equals("type"))
						{
							if(value.equals("apk"))
							{
								
							}
							else if(value.equals("lib"))
							{
								
							}
							else if(value.equals("res"))
							{
								
							}
						}
						else if(name.equals("url"))
						{
							json.put(KEY_SO_URL, value);
						}
						else if(name.equals("dmp"))
						{
							
						}
						else if(name.equals("ver"))
						{
							
						}
					}
				}
				break;
			case XmlPullParser.END_TAG:
				String endName = parser.getName();
				
				break;
			}
			eventType = parser.next();
		}
		
		compare(json);
	}

	private void compare(final JSONObject json)
	{
		try {		
			if(json.isNull(KEY_CDN_URL) || json.isNull(KEY_SO_URL) || json.isNull(KEY_NEED_UPDATE))
			{
				mOnMyCallBack.onReceive("yes", 0, json);
				return;
			}
			
			String temp_lib = SuperTools.getInstance().readLocalFile(KEY_CLIENT_VERSION_LIB);
			String temp_res = SuperTools.getInstance().readLocalFile(KEY_CLIENT_VERSION_RES);

			if(SuperTools.getStringType(temp_lib) != 0)
				temp_lib = "";
			if(SuperTools.getStringType(temp_res) != 0)
				temp_res = "";
			
			int clientVersion_lib = temp_lib.equals("") ? 1509161500 : Integer.valueOf(temp_lib);
			int clientVersion_res = temp_res.equals("") ? 1509161500 : Integer.valueOf(temp_res);
			int newestVersion_lib = json.getInt(KEY_NEWEST_VERSION_LIB);
			int newestVersion_res = json.getInt(KEY_NEWEST_VERSION_RES);
			boolean needUpdate = json.getBoolean(KEY_NEED_UPDATE);
			
			boolean needUpdate_lib = false;
			if (clientVersion_lib < newestVersion_lib)
				needUpdate_lib = true;
			else
				needUpdate_lib = false;
			json.put(KEY_NEED_UPDATE_LIB, needUpdate_lib);
			
			boolean needUpdate_res = false;
			if (clientVersion_res < newestVersion_res)
				needUpdate_res = true;
			else
				needUpdate_res = false;
			json.put(KEY_NEED_UPDATE_RES, needUpdate_res);
			
			//对比版本
			if (needUpdate_lib || needUpdate_res)
			{
				//提示有更新
				mActivity.runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub

//						SCDialog.create(mActivity, "更新提示", "游戏有新的资源更新!", "确定", "", new OnMyClickedListener() {
//							
//							@Override
//							public void onPositive(JSONObject data) {
//								// TODO Auto-generated method stub
//								
//							}
//							
//							@Override
//							public void onNegative(JSONObject data) {
//								// TODO Auto-generated method stub
//								mOnMyCallBack.onReceive("yes", 1, json);
//							}
//						}).show();
						mOnMyCallBack.onReceive("yes", 1, json);
					}
				});
			}
			else
				mOnMyCallBack.onReceive("no", -1, json);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}//新的版本号
		
	}
	
	private void checkAssertLibAndRes() throws IOException, NameNotFoundException
	{
		//如果系统区没有lib文件,先从assert解压过去
		ApplicationInfo ai = mActivity.getPackageManager().getApplicationInfo(
				mActivity.getPackageName(), PackageManager.GET_META_DATA);
        Bundle bundle = ai.metaData;
        String libName = SuperTools.getInstance().getSystemPath()
        		+ "lib" + bundle.getString("android.app.lib_name") + ".so";
      

		String temp_lib = SuperTools.getInstance().readLocalFile(KEY_CLIENT_VERSION_LIB);
		if(SuperTools.getStringType(temp_lib) != 0)
			temp_lib = "";
		//当前lib版本号
		int clientVersion_lib = temp_lib.equals("") ? 1509161500 : Integer.valueOf(temp_lib);
		L.d("=======curClientVersion_lib:" + clientVersion_lib);
		
    	String[] ff = mActivity.getAssets().list("");
		for (String f : ff) 
		{
		    if (f.startsWith("lib") && f.length() == 13) 
			{
		    	L.d("=======what the fuck lib? fileName:" + f);
		    	//如果没有so文件,就解压assert的过去
		    	if( !SuperTools.getInstance().isExistFile(libName) )
		        {
					String libVersion = f.substring(3);
					String targetFile = f + "/" + "lib" + bundle.getString("android.app.lib_name") + ".zip";
					InputStream is = mActivity.getAssets().open(targetFile);
					if(unzipFile(is, SuperTools.getInstance().getSystemPath()))
					{
						SuperTools.getInstance().writeLocalFile(KEY_CLIENT_VERSION_LIB, "" + libVersion);
					}
				}
		    	else
		    	{
		    		//如果存在,就比对一下版本号
		    		String libVersion = f.substring(3);
		    		if(SuperTools.getStringType(libVersion) != 0)
		    			continue;
					//如果内存的版本号比assert的小,也要覆盖处理
		    		int tempLib = Integer.valueOf(libVersion);
					if(clientVersion_lib < tempLib)
					{
						String targetFile = f + "/" + "lib" + bundle.getString("android.app.lib_name") + ".zip";
						InputStream is = mActivity.getAssets().open(targetFile);
						if(unzipFile(is, SuperTools.getInstance().getSystemPath()))
						{
							SuperTools.getInstance().writeLocalFile(KEY_CLIENT_VERSION_LIB, "" + libVersion);
						}
					}
		    	}
	        }
		    else if(f.startsWith("res"))
			{
		    	L.d("=======what the fuck res? fileName:" + f);
				String resVersion = f.substring(3);
				String ret = SuperTools.getInstance().readLocalFile(KEY_CLIENT_VERSION_RES);
				if(ret.equals(""))
				{
					//如果数据中没有res版本号,则写入默认
					SuperTools.getInstance().writeLocalFile(KEY_CLIENT_VERSION_RES, resVersion);
				}
			}
		}
	}
	
	public static boolean unzipFile(InputStream stream, String tpFilePath)
	{
		try {
			java.util.zip.ZipInputStream inZip = new java.util.zip.ZipInputStream(stream);
			ZipEntry zipEntry = inZip.getNextEntry();
			
			String targetFileName = tpFilePath + zipEntry.getName();
			String TargetFileName_tp = tpFilePath + zipEntry.getName() + "_tp";
			File tpTargetFileName = new File(TargetFileName_tp);
			if ( tpTargetFileName.exists() )
				tpTargetFileName.delete();
			
			byte[] buffer = new byte[10240];
			try {
				FileOutputStream out = new java.io.FileOutputStream(TargetFileName_tp);
				int len;
				while ((len = inZip.read(buffer)) != -1) 
				{
					out.write(buffer, 0, len);
					out.flush();
				}
				
				out.close();
				
				//改回正常的名字
				File oldf = new File(TargetFileName_tp);
				File newf = new File(targetFileName);
				oldf.renameTo(newf);
				
				return true;
				
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
	
}
